from rest_framework import viewsets, views
from rest_framework.response import Response
from django.db.models import Count, Sum, Max, Case, When, F

from library_app.models import Category, Author, Book
from library_app.serializers import CategorySerializer, AuthorSerializer, BookReadSerializer, BookWriteSerializer


class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()

    def get_serializer_class(self):
        if self.request.method in ['GET', 'HEAD']:
            return BookReadSerializer
        else:
            return BookWriteSerializer


class CategoryViewSet(viewsets.ModelViewSet):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer


class AuthorViewSet(viewsets.ModelViewSet):
    queryset = Author.objects.all()
    serializer_class = AuthorSerializer


# 统计接口一般用不到序列化器，所以这里就直接使用APIView
class StatisticsViewSet(views.APIView):
    """ 统计数据 """

    def get(self, request):
        # 这个方式方式在处理大量的数据时耗时相对更少，用户等到时间更短。

        # 统计书本总数量和总价格
        # book_total = Book.objects.aggregate(
        #     book_total=Count("id"),  # 书籍的总数量
        #     total_cost=Sum("price"),  # 书籍的总成本
        # )

        # Book中的owned字段如果是拥有的数量的话，统计应该这么写
        book_total = Book.objects.annotate(total_price=F("price") * F("owned")).aggregate(
            book_total=Count("id"),  # 书籍的总数量
            total_cost=Sum("total_price"),  # 书籍的总成本
        )

        # 统计书本最多的作者
        author = Author.objects.annotate(book_number=Count("book"))
        max_number = author.aggregate(max_number=Max("book_number")).get("max_number") or 0
        author_name = author.filter(book_number=max_number).values("name")

        # 统计书本最多的分类
        category = Category.objects.annotate(book_number=Count("book"))
        max_number = category.aggregate(max_number=Max("book_number")).get("max_number") or 0
        category_title = category.filter(book_number=max_number).values("title")

        return Response({
            **book_total,
            "most_books_author": [i["name"] for i in author_name],
            "most_books_category": [i["title"] for i in category_title],
        })
